/**
 * 
 */
package edu.gtcfla.km.platform.appmodules.web.filter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.cas.CasFilter;
import org.apache.shiro.subject.Subject;

import edu.gtcfla.km.security.token.CasUserToken;

/**
 * @author vison
 *
 */
public class EduCasFilter extends CasFilter {

    // the name of the parameter service ticket in url
    private static final String TICKET_PARAMETER = "ticket";	

    @Override
    protected boolean executeLogin(ServletRequest request, ServletResponse response) throws Exception {
        AuthenticationToken token = createToken(request, response);
        if (token == null) {
            String msg = "createToken method implementation returned null. A valid non-null AuthenticationToken " +
                    "must be created in order to execute a login attempt.";
            throw new IllegalStateException(msg);
        }
        
        boolean onloginResult = false;
        
        try {
            Subject subject = getSubject(request, response);
            
            boolean authenticated  = subject.isAuthenticated();
            
            HttpServletRequest httpReq = (HttpServletRequest)request;
            StringBuffer sb = httpReq.getRequestURL();
            
            System.out.println(sb);
            
            if (!authenticated) {
                subject.login(token);
                onloginResult = onLoginSuccess(token, subject, request, response);
                return onloginResult;            	
            } 
            
            // --- if authenticated ---
            else {
            	
            	System.out.println("have login ");
            	return true;
            }

        } catch (AuthenticationException e) {
            return onLoginFailure(token, e, request, response);
        }
    }    
    
    @Override
    protected boolean onLoginSuccess(AuthenticationToken token, Subject subject,
            ServletRequest request, ServletResponse response) throws Exception {
    		return true;
    }

    @Override
	protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e,
	            ServletRequest request, ServletResponse response) {
		return false;
	}
    
    
    
    @Override
    protected AuthenticationToken createToken(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletRequest httpRequest = (HttpServletRequest) request;

        java.security.Principal principal = (java.security.Principal)httpRequest.getUserPrincipal();         
        
		String casId = principal.getName();
		
		CasUserToken userToken = new CasUserToken(casId);
        return userToken;
    }	
	
}
